#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <errno.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#define N 64

int main(int argc, char *argv[])
{
        // 0定义变量
    int sockfd, clientfd;
    char buf[N];
    int addrlen = sizeof(struct sockaddr);
    struct sockaddr_in addr, clientaddr;
    int nbytes;

    if(argc != 3) {
        printf("usage: %s <ip> <port>\n", argv[0]);
        return -1;
    }

        // 1创建一个套接字--socket
    sockfd = socket(AF_INET, SOCK_STREAM, 0);
    if(sockfd < 0) {
        perror("socket err");
        exit(-1);
    }

        // 2定义套接字地址--sockaddr_in
    bzero(&addr, addrlen);
    addr.sin_family = AF_INET;
    addr.sin_addr.s_addr = INADDR_ANY;
    addr.sin_port = htons(atoi(argv[2]));

        // 3绑定套接字--bind
    if(bind(sockfd, (struct sockaddr *)&addr, addrlen) < 0) {
        perror("bind err");
        exit(-1);
    }

        // 4启动监听--listen
    if(listen(sockfd, 5) < 0) {
        perror("listen err");
        exit(-1);
    }

        // 5接收连接--accept
    clientfd = accept(sockfd, (struct sockaddr *)&clientaddr, &addrlen);
    if(clientfd < 0) {
        perror("accept err");
        exit(-1);
    }

    int len = 0;
    int i;

    // 6收发数据--recv/send
    while (1) {
        //先接收4个字节的包总长
        nbytes = recv(clientfd, &len, 4, 0);
        if(nbytes == 0){
            break;
        }

        //处理字节序
        len = ntohl(len);
        printf("len = 0x%x\n", len);

        recv(clientfd, buf, len, 0);
        for(i=0; i<len; i++){
            printf("%c", buf[i]);
        }
        printf("\n");
    }

        // 7关闭连接--close
    close(clientfd);
    close(sockfd);
}
